package com.ht.demo.service.system;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 获取spring上下文对象，通过此类获取容器中的对象
 * @author huangxian
 * @date 2022/5/20 11:22
 */
@Component
public class AppContext implements ApplicationContextAware, BeanFactoryPostProcessor {
    //上下文
    private static ApplicationContext applicationContext;

    /** Spring应用上下文环境 */
    private static ConfigurableListableBeanFactory beanFactory;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        AppContext.applicationContext = applicationContext;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        AppContext.beanFactory = beanFactory;
    }

    public static <T>  T getBean(Class<T> clz){
        return applicationContext.getBean(clz);
    }
    /**
     * 获取对象
     *
     * @param name
     * @return Object 一个以所给名字注册的bean的实例
     * @throws org.springframework.beans.BeansException
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T) beanFactory.getBean(name);
    }
}
